//
//  RushVC.m
//  K-Music
//
//  Created by CHUN on 15/12/27.
//  Copyright © 2015年 CHUN. All rights reserved.
//

#import "RushVC.h"
#import "ChinaVC.h"
#import "List_China.h"
#import "AllMusicVC.h"
#import "K_ROOMVC.h"

#import "RuningData.h"

#import "MyAllText.h"

#import "SameWay.h"
#import "RushStepCell.h"

#import "UIImageView+WebCache.h"

#import "YYplayerVC.h"
#import "WHScrollAndPageView.h"

static NSString * const CellIdentifier = @"RushCvCell";
static NSString * const HeaderIdentifier = @"HeaderIdentifier";

@interface RushVC ()<UIScrollViewDelegate,WHcrollViewViewDelegate>{
    
    UICollectionView * RustVC ;

    NSMutableArray * all_Data ;

    WHScrollAndPageView * _whView;
    
}

@property (nonatomic, strong) RAMCollectionViewFlemishBondLayout *collectionViewLayout;


@end

@implementation RushVC

-(void)viewWillAppear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = NO;
    [self set_right_Button];

}
- (void)viewWillDisappear:(BOOL)animated
{
//    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self get_QGB];
    
    [self createrUI];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithIcon:@"play" highIcon:@"play" target:self action:@selector(play_play)];
    
    
    [self get_QUYU];
    [self get_all_music];
    

    
}


- (void)set_right_Button
{
    [self get_area_Data];
    
    UIButton *leftbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftbtn.frame = CGRectMake(0, 0, 40, 35);
    [leftbtn setImage:[UIImage imageNamed:@"icon_homepage_downArrow"] forState:UIControlStateNormal];
    [leftbtn setImage:[UIImage imageNamed:@"icon_homepage_upArrow"] forState:UIControlStateSelected];
    
    leftbtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    
    [leftbtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -35, 0, 0)];
    
    leftbtn.imageEdgeInsets = UIEdgeInsetsMake(0, 28, 0, 0);
    
    if (strIsEmpty([User_information conversion].area_city)) {
        [User_information conversion].area_city = @"北京";
    }
    
    [leftbtn setTitle:[User_information conversion].area_city forState:UIControlStateNormal];
    leftbtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [leftbtn addTarget:self action:@selector(To_Admin_area) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftbtn];

}

- (void)topAdTap:(UITapGestureRecognizer *)sender
{
    UITapGestureRecognizer * tap = (UITapGestureRecognizer *)sender;
    UIImageView *viewg = (UIImageView *) tap.view;
    NSInteger ined = viewg.tag - 68402;
    NSLog(@"%ld",ined);
    
    [self play_play];
}

- (void)To_Admin_area
{
    Admin_area_VC * area = [[Admin_area_VC alloc]init];
    [self.navigationController pushViewController:area animated:NO];
}


- (void)play_play
{
    NSLog(@"play");
    //    [MBProgressHUD showErrorWithStatus:@"播放器" toView:self.view];
    
    YYplayerVC* yy = [[YYplayerVC alloc]init];
    
    yy.hidesBottomBarWhenPushed = YES;
    
    yy.musicData= [User_information conversion].musicData[0];
    
    [yy setTracks:[Track remoteTracks]];
    
    [self.navigationController pushViewController:yy animated:NO];
    
}

- (void)back_back
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark-----最火榜数据  全国
-(void)get_QGB{
    
    [MBProgressHUD showWithStatus:@"加载中..." toView:self.view];
    
    [SameWay downloadData:@"A" andCallback:^(id obj) {
        NSLog(@"===========:%@",obj);
        
        all_Data=[NSMutableArray array];
        
        all_Data = obj;
        NSLog(@"%@",all_Data);
        
        [User_information conversion].QGB_Data = obj;
        
        [RustVC reloadData];
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (void)get_area_Data
{
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    
    NSString*infoStr11=[NSString stringWithFormat:@"/api/record_rank/area_rank/%@/",[User_information conversion].adminAreaCode];
    
    NSString *intactURL = [MyBaseUrl stringByAppendingString:infoStr11];
    
    NSString * token = [FileStorage NSUserDefault_getObjectForKey:access_token];
    
    //创建请求
    manager.requestSerializer =[AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:@"application/json"
                     forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[NSString stringWithFormat: @"Bearer %@",token]
                     forHTTPHeaderField:@"Authorization"];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:intactURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        
        NSLog(@"%@",dic);
        
        NSLog(@"resultCode:%@",dic[@"resultCode"]);
        NSArray*content=dic[@"body"][@"content"];
        
        NSArray * Datas = [A_Music objectArrayWithKeyValuesArray:content];
        [User_information conversion].Area_Data = [NSMutableArray arrayWithArray:Datas];
        
        [RustVC reloadData];
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
        [MBProgressHUD showErrorWithStatus:@"数据获取失败" toView:self.view];
        
    }];
    
}

-(void)createrUI{
    
    NSArray*textData;
    
    textData=[NSArray arrayWithObjects:@"C_1",@"C_2",@"C_3",@"C_4",nil];
    
    NSArray*titleData=[NSArray arrayWithObjects:@"全国榜",@"排行榜",@"人气榜",@"K歌包房",nil];
    
    UIView *headview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 100)];
    headview.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:headview];
    
    for (int i=0; i<3; i++) {
        
        UIImageView*img=[[UIImageView alloc]init];
        img.frame = CGRectMake((WIDTH/6-30)+WIDTH/3*i, 10, 60, 60);
        img.image=[UIImage imageNamed:[NSString stringWithFormat:@"%@",textData[i]]];
        [headview addSubview: img];
        
        UILabel*text=[[UILabel alloc]initWithFrame:CGRectMake(i*headview.frame.size.width/3, CGRectGetMaxY(img.frame)+5, headview.frame.size.width/3, 20)];
        text.textAlignment=NSTextAlignmentCenter;
        text.text=[NSString stringWithFormat:@"%@",titleData[i]];
        [headview addSubview: text];

        UIButton*img_btn=[UIButton buttonWithType:UIButtonTypeCustom];
        img_btn.frame=CGRectMake(i*headview.frame.size.width/3, 0, headview.frame.size.width/3, HEIGHT/10 );
        img_btn.tag=i ;
        [img_btn addTarget:self action:@selector(TopButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [headview addSubview:img_btn];
        
    }

    self.collectionViewLayout = [[RAMCollectionViewFlemishBondLayout alloc] init];
    self.collectionViewLayout.delegate = self;
    self.collectionViewLayout.numberOfElements = 2;
    self.collectionViewLayout.highlightedCellHeight = HEIGHT/4;
    self.collectionViewLayout.highlightedCellWidth = WIDTH/2;
    
    RustVC = [[UICollectionView alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(headview.frame) , WIDTH  , HEIGHT- CGRectGetMaxY(headview.frame)- 49 - 64) collectionViewLayout:self.collectionViewLayout];
    
    RustVC.delegate = self;
    RustVC.dataSource = self;
    RustVC.backgroundColor = [UIColor whiteColor];
    
    [RustVC registerClass:[RushCvCell class] forCellWithReuseIdentifier:CellIdentifier];
    [RustVC registerClass:[RAMCollectionAuxView class] forSupplementaryViewOfKind:RAMCollectionViewFlemishBondHeaderKind withReuseIdentifier:HeaderIdentifier];
    
    [self.view addSubview:RustVC];

}

-(void)TopButtonClick:(UIButton*)btn{
    
    NSLog(@"--切换排行榜--");
    
    if (btn.tag==0) {
        ChinaVC*cc=[[ChinaVC alloc]init];
        cc.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:cc animated:NO];
    }else if(btn.tag==1)
    {
        
#warning --总榜--
        NSArray * viewControllers = @[[rush_list_one class], [rush_list_two class],[rush_list_three class]];
        
        NSArray *titles = @[@"作品榜",@"歌手榜",@"财富榜"];
        
        WMPageController *pageVC = [[WMPageController alloc] initWithViewControllerClasses:viewControllers andTheirTitles:titles];
        pageVC.viewFrame = CGRectMake(0, 0, WIDTH, HEIGHT);
        pageVC.pageAnimatable = YES;
        pageVC.menuItemWidth = 100;
        pageVC.menuHeight = 50;
        pageVC.titleSizeSelected = 15;
        pageVC.titleColorSelected = [UIColor orangeColor];
        pageVC.postNotification = YES;
        pageVC.bounces = YES;
        pageVC.menuViewStyle = WMMenuViewStyleLine;
        pageVC.hidesBottomBarWhenPushed = YES;
        
        pageVC.navigationItem.title = @"总榜";
        pageVC.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"back" highIcon:@"back" target:self action:@selector(back_back)];
        pageVC.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithIcon:@"play" highIcon:@"play" target:self action:@selector(play_play)];

        [self.navigationController pushViewController:pageVC animated:NO];
        
    }
    
    else if(btn.tag==2)
    {
        List_China * cc = [[List_China alloc]init];
        cc.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:cc animated:NO];
    }
    else if(btn.tag==3){
        
        K_ROOMVC * room =[[K_ROOMVC alloc]init];
        room.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:room animated:NO];
    }
    
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [User_information conversion].Area_Data.count-1;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    [RustVC registerClass:[RushCvCell class] forCellWithReuseIdentifier:@"RushCvCell"];
    
    RushCvCell*cell=(RushCvCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"RushCvCell" forIndexPath:indexPath];

    A_Music * data =[[A_Music alloc]init];
    
    data  = [User_information conversion].Area_Data[indexPath.row+1];
    
    //1头像  底图片
    [cell.icon_image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",data.avatar]] placeholderImage:
     nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
         
         cell.icon_image.image = [cell.icon_image.image imageByCroppingWithStyle:10];
         
     }];
    
    //2序号
    cell.list_num_label.text = [NSString stringWithFormat:@"%ld.",(long)indexPath.row+2
                                ];

    //3 歌曲名
    cell.song_name.text = [NSString stringWithFormat:@"%@",data.name];

    //4 用户名 + 3 图标
//    cell.my_name.text=[NSString stringWithFormat:@"%@",data.userId];
    
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",data.userId]];

    //(1)VIP icon
    // 添加表情
    NSTextAttachment *vip = [[NSTextAttachment alloc] init];
    // 设置图片大小
    vip.bounds = CGRectMake(2, 0, 25, 12.5);
    // 表情图片
    vip.image = [UIImage imageNamed:@"vip_one"];
 
    // 创建带有图片的富文本
    NSAttributedString * vip_Icon = [NSAttributedString attributedStringWithAttachment:vip];
    
    [attri appendAttributedString:vip_Icon];
    
    //(2)fortune
    NSTextAttachment * fortune = [[NSTextAttachment alloc]init];
    
    fortune.bounds = CGRectMake(2, -5, 25, 25);
    
    [cell.star_one sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",data.fortuneLevelIcon]]];
   
    fortune.image = cell.star_one.image ;

    NSAttributedString * fortuneLevel_Icon = [NSAttributedString attributedStringWithAttachment:fortune];
    
    [attri appendAttributedString:fortuneLevel_Icon];
    
     //(3)singer
    NSTextAttachment * singer = [[NSTextAttachment alloc]init];
    
    singer.bounds = CGRectMake(2, -5, 25, 25);
    
    [cell.star_two sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",data.singerLevelIcon]]];

    singer.image = cell.star_two.image ;

    NSAttributedString * singerLevel_Icon = [NSAttributedString attributedStringWithAttachment:singer];
    
    [attri appendAttributedString:singerLevel_Icon];
    
    // 用label的attributedText属性来使用富文本
    cell.user_name.attributedText = attri;

    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"%ld",indexPath.row);

    [self play_play];
    
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;
{
    UICollectionReusableView * Header_View;
    
    if (kind == RAMCollectionViewFlemishBondHeaderKind) {
        
        Header_View = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:HeaderIdentifier forIndexPath:indexPath];
        
        A_Music * data =[[A_Music alloc]init];
        
        data  = [User_information conversion].Area_Data[0];
        
        //1头像  底图片
        [((RAMCollectionAuxView *)Header_View).icon_image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",data.avatar]] placeholderImage:
         nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
             
             ((RAMCollectionAuxView *)Header_View).icon_image.image = [((RAMCollectionAuxView *)Header_View).icon_image.image imageByCroppingWithStyle:10];
             
         }];
        
        //2序号
        ((RAMCollectionAuxView *)Header_View).list_num_label.text = [NSString stringWithFormat:@"%ld.",(long)indexPath.row+1
                                                                     ];
        //3 歌曲名
        ((RAMCollectionAuxView *)Header_View).song_name.text = [NSString stringWithFormat:@"%@",data.name];
        
        //4 用户名 + 3 图标
        //    cell.my_name.text=[NSString stringWithFormat:@"%@",data.userId];
        
        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",data.userId]];
        
        //(1)VIP icon
        // 添加表情
        NSTextAttachment *vip = [[NSTextAttachment alloc] init];
        // 设置图片大小
        vip.bounds = CGRectMake(2, 0, 25, 12.5);
        // 表情图片
        vip.image = [UIImage imageNamed:@"vip_one"];
        
        // 创建带有图片的富文本
        NSAttributedString * vip_Icon = [NSAttributedString attributedStringWithAttachment:vip];
        
        [attri appendAttributedString:vip_Icon];
        
        //(2)fortune
        NSTextAttachment * fortune = [[NSTextAttachment alloc]init];
        
        fortune.bounds = CGRectMake(2, -5, 25, 25);
        
        [((RAMCollectionAuxView *)Header_View).star_one sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",data.fortuneLevelIcon]]];
        
        fortune.image = ((RAMCollectionAuxView *)Header_View).star_one.image ;
        
        NSAttributedString * fortuneLevel_Icon = [NSAttributedString attributedStringWithAttachment:fortune];
        
        [attri appendAttributedString:fortuneLevel_Icon];
        
        //(3)singer
        NSTextAttachment * singer = [[NSTextAttachment alloc]init];
        
        singer.bounds = CGRectMake(2, -5, 25, 25);
        
        [ ((RAMCollectionAuxView *)Header_View).star_two sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",data.singerLevelIcon]]];
        
        singer.image = ((RAMCollectionAuxView *)Header_View).star_two.image ;
        
        NSAttributedString * singerLevel_Icon = [NSAttributedString attributedStringWithAttachment:singer];
        
        [attri appendAttributedString:singerLevel_Icon];
        
        // 用label的attributedText属性来使用富文本
        ((RAMCollectionAuxView *)Header_View).user_name.attributedText = attri;
        
    }
    
    return Header_View;
    
}
#pragma mark - RAMCollectionViewVunityLayoutDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(RAMCollectionViewFlemishBondLayout *)collectionViewLayout estimatedSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(CGRectGetWidth(RustVC.frame), HEIGHT/4+20);
}

- (RAMCollectionViewFlemishBondLayoutGroupDirection)collectionView:(UICollectionView *)collectionView layout:(RAMCollectionViewFlemishBondLayout *)collectionViewLayout highlightedCellDirectionForGroup:(NSInteger)group atIndexPath:(NSIndexPath *)indexPath
{
    RAMCollectionViewFlemishBondLayoutGroupDirection direction;
    
    if (indexPath.row % 2) {
        direction = RAMCollectionViewFlemishBondLayoutGroupDirectionRight;
    } else {
        direction = RAMCollectionViewFlemishBondLayoutGroupDirectionLeft;
    }
    
    return direction;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark-----城市列表
- (void)get_QUYU
{
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    
    NSString * userId = [NSString stringWithFormat:@"%@",[FileStorage NSUserDefault_getObjectForKey:User_id]];
    
    NSString*infoStr11=[NSString stringWithFormat:@"/api/admin_area"];
    
    NSString *intactURL = [MyBaseUrl stringByAppendingString:infoStr11];
    
    NSString * token = [FileStorage NSUserDefault_getObjectForKey:access_token];
    
    //创建请求
    manager.requestSerializer =[AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:@"application/json"
                     forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[NSString stringWithFormat: @"Bearer %@",token]
                     forHTTPHeaderField:@"Authorization"];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:intactURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        
        NSLog(@"%@",dic);
        
        NSArray * arr = dic[@"body"][@"content"];
        NSArray * Datas = [Admin_area_mode objectArrayWithKeyValuesArray:arr];
        [User_information conversion].admin_area = [NSMutableArray arrayWithArray:Datas];
        
        NSLog(@"%@",arr);
        
        [User_information conversion].adminAreaCode = [arr[0] objectForKey:@"adminAreaCode"];
        [User_information conversion].area_city = [arr[0] objectForKey:@"city"];
        
        //城市列表
        [self get_area_Data];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
        [MBProgressHUD showErrorWithStatus:@"数据获取失败" toView:self.view];
        
    }];
}



#pragma mark----- 所有歌曲
- (void)get_all_music
{
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    
    NSString*infoStr11=[NSString stringWithFormat:@"/api/song?page=0&size=20&sort=createdDate,DESC"];
    
    NSString *intactURL = [MyBaseUrl stringByAppendingString:infoStr11];
    
    NSString * token = [FileStorage NSUserDefault_getObjectForKey:access_token];
    
    //    创建请求
    manager.requestSerializer =[AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:@"application/json"
                     forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[NSString stringWithFormat: @"Bearer %@",token]
                     forHTTPHeaderField:@"Authorization"];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:intactURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        
        NSLog(@"成功GET --> %@", dic);
        
        if ([dic[@"errorCode"]intValue] != 1404 )
        {
            NSArray*content=dic[@"body"][@"content"];
            
            _musicingData = [NSMutableArray array];
            
            for (NSDictionary * Data in content) {
                musicing_mode * mode =[[musicing_mode alloc]init];
                
                mode.accompanyUrl =Data[@"accompanyUrl"];
                mode.coverImage =Data[@"coverImage"];
                mode.createdBy =Data[@"createdBy"];
                mode.createdDate =Data[@"createdDate"];
                mode.descriptiond =Data[@"description"];
                mode.heat =Data[@"heat"];
                mode.aid =Data[@"id"];
                
                mode.lastModifiedBy =Data[@"lastModifiedBy"];
                mode.lastModifiedDate =Data[@"lastModifiedDate"];
                
                mode.lyric =Data[@"lyric"];
                mode.name =Data[@"name"];
                mode.singerName =Data[@"singerName"];
                mode.size =Data[@"size"];
                
                mode.url =Data[@"url"];
                
                [mode fixedString];
                
                [_musicingData addObject:mode];
                
            }
        }else{
            
            _musicingData = nil;
            
        }
        [User_information conversion].SING_Data = [_musicingData copy];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
        
        [MBProgressHUD showErrorWithStatus:@"获取数据失败" toView:self.view];
        
    }];
}



@end
